import wx

from event_bus import EventBus
from exports import create_group_engine, BaseGrouping
from uis import SampleExport
from view_models import project_state
from wxutils import call_after


class ExportSample(SampleExport):
    engine: BaseGrouping

    def __init__(self, parent=None):
        super().__init__(parent)

        self.Bind(wx.EVT_BUTTON, self.on_export_samples, self.start_export)

        EventBus().register_topic(topic="switched_to_export", handler=self.refresh_export)
        EventBus().register_topic(topic="export_job_done", handler=self.progress_forward)
        EventBus().register_topic(topic="export_failed", handler=self.process_export_failure)

    def refresh_export(self, _):
        self.marker_list.Clear()
        self.marker_list.SetItems(sorted({c for c in project_state.categories}))

    def on_export_samples(self, _):
        """执行项目输出任务，任务总量=各特征样本数量"""
        if len(self.marker_list.GetCheckedItems()) == 0:
            wx.MessageBox("请先选择要使用的特征类别。", "未选择特征")
            return
        # self.marker_list.Enable(False)
        self.export_progress.SetValue(0)
        selected_categories = {c for c in self.marker_list.GetCheckedStrings()}
        self.engine = create_group_engine(project_state.current,
                                          selected_categories,
                                          self.pad_sample.GetValue(),
                                          self.resize_sample.GetValue(),
                                          self.use_csv_group.GetValue())
        self.export_progress.SetRange(self.engine.calculate_works())
        self.engine.write_categories()
        self.engine.split_group()
        self.engine.generate_samples()

    @call_after
    def progress_forward(self, _):
        self.export_progress.SetValue(self.export_progress.GetValue() + 1)
        if self.export_progress.GetValue() == self.export_progress.GetRange():
            wx.MessageBox("项目已完成导出，请到输出目录中查看。", "导出完成")
            self.start_export.Enable(True)
            self.export_progress.SetValue(0)
            self.use_csv_group.Enable(True)
            self.use_directory_group.Enable(True)

    @call_after
    def process_export_failure(self, event):
        from pprint import pprint
        pprint(event)
        self.engine.cancel()
        self.start_export.Enable(True)
        self.export_progress.SetValue(0)
        self.use_csv_group.Enable(True)
        self.use_directory_group.Enable(True)
        wx.MessageBox("项目导出失败！", "导出失败")
